<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use App\Models\Admin;
use Illuminate\Support\Facades\Auth;

class AuthController extends Controller
{
    /**
     * 显示登录表单
     */
    public function showLoginForm()
    {
        return view('admin.auth.login');
    }
    
    /**
     * 处理管理员登录
     */
    public function login(Request $request)
    {
        $request->validate([
            'username' => 'required|string',
            'password' => 'required|string',
        ]);
        
        // 查找管理员
        $admin = Admin::where('username', $request->username)->first();
        
        if (!$admin || !Hash::check($request->password, $admin->password)) {
            return back()->withErrors([
                'username' => '用户名或密码错误',
            ]);
        }
        
        // 保存管理员ID到会话
        $request->session()->put('admin_id', $admin->id);
        $request->session()->put('admin_name', $admin->name);
        
        return redirect()->route('admin.dashboard');
    }
    
    /**
     * 退出登录
     */
    public function logout(Request $request)
    {
        $request->session()->forget(['admin_id', 'admin_name']);
        return redirect()->route('admin.login');
    }
}
